package com.tiancheng.trade.settlement.util;

import com.tiancheng.trade.settlement.exception.error.BusinessErrorInfoEnum;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

@Slf4j
public class SignUtils {

    private static final String ALGORITHM = "RSA";

    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    private static final String SIGN_SHA256RSA_ALGORITHMS = "SHA256WithRSA";

    private static final String DEFAULT_CHARSET = "UTF-8";

    private static String getAlgorithms(boolean rsa2) {
        return rsa2 ? SIGN_SHA256RSA_ALGORITHMS : SIGN_ALGORITHMS;
    }

    /**
     * 签名
     *
     * @param content    内容
     * @param privateKey 私钥
     * @param rsa2       是否是rsa2
     * @return
     */
    public static String sign(String content, String privateKey, boolean rsa2) {
        try {
            java.security.Security.addProvider(
                    new org.bouncycastle.jce.provider.BouncyCastleProvider()
            );
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                    Base64.getDecoder().decode(privateKey));
            KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature
                    .getInstance(getAlgorithms(rsa2));
            signature.initSign(priKey);
            signature.update(content.getBytes(DEFAULT_CHARSET));
            byte[] signed = signature.sign();
            return Base64.getEncoder().encodeToString(signed);
        } catch (Exception e) {
            log.error(e.getMessage());
            BusinessErrorInfoEnum.SIGN_UTILS_SIGN_ERROR.assertFail();
        }
        return null;
    }

    /**
     * 获取私钥
     *
     * @param filePath 路径
     * @return
     */
    public static String getKey(String filePath) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String s = br.readLine();
            String str = "";
            if (s != null && s.charAt(0) == '-') {
                s = br.readLine();
            }
            while (s != null && s.charAt(0) != '-') {
                str += s;
                s = br.readLine();
            }
            BusinessErrorInfoEnum.SIGN_UTILS_KEY_NULL.assertNotEmpty(str);
            return str;
        } catch (IOException e) {
            log.error(e.getMessage());
            BusinessErrorInfoEnum.SIGN_UTILS_KEY_FILE_ERROR.assertFail();
        }
        return null;
    }

}
